<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>浅析React children | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="React,React.cloneElement,">
  

  <meta name="description" content="一、子组件 我们有一个组件 &amp;lt;Grid /&amp;gt; 包含了几个组件 &amp;lt;Row /&amp;gt; 。你可能会这么使用它  &amp;lt;Grid&amp;gt;  &amp;lt;Row /&amp;gt;  &amp;lt;Row /&amp;gt;  &amp;lt;Row /&amp;gt;&amp;lt;/Grid&amp;gt;  这三个 Row 组件都成为了 Grid 的 props.children 。使用一个表达式容器，父组件就能够渲染它们的子组件  c">
<meta name="keywords" content="React,React.cloneElement">
<meta property="og:type" content="article">
<meta property="og:title" content="浅析React children">
<meta property="og:url" content="http://blog.poetries.top/2019/09/01/react-children/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、子组件 我们有一个组件 &amp;lt;Grid /&amp;gt; 包含了几个组件 &amp;lt;Row /&amp;gt; 。你可能会这么使用它  &amp;lt;Grid&amp;gt;  &amp;lt;Row /&amp;gt;  &amp;lt;Row /&amp;gt;  &amp;lt;Row /&amp;gt;&amp;lt;/Grid&amp;gt;  这三个 Row 组件都成为了 Grid 的 props.children 。使用一个表达式容器，父组件就能够渲染它们的子组件  c">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-08-15T04:25:31.930Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="浅析React children">
<meta name="twitter:description" content="一、子组件 我们有一个组件 &amp;lt;Grid /&amp;gt; 包含了几个组件 &amp;lt;Row /&amp;gt; 。你可能会这么使用它  &amp;lt;Grid&amp;gt;  &amp;lt;Row /&amp;gt;  &amp;lt;Row /&amp;gt;  &amp;lt;Row /&amp;gt;&amp;lt;/Grid&amp;gt;  这三个 Row 组件都成为了 Grid 的 props.children 。使用一个表达式容器，父组件就能够渲染它们的子组件  c">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、子组件"><span class="toc-text">一、子组件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、任何东西都能是一个child"><span class="toc-text">二、任何东西都能是一个child</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、child-的功能"><span class="toc-text">三、child 的功能</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、操作children"><span class="toc-text">四、操作children</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-循环"><span class="toc-text">4.1 循环</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-计数"><span class="toc-text">4.2 计数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-转换为数组"><span class="toc-text">4.3 转换为数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4-执行单一child"><span class="toc-text">4.4 执行单一child</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、编辑children"><span class="toc-text">五、编辑children</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1-改变children的属性"><span class="toc-text">5.1 改变children的属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-React-cloneElement克隆元素"><span class="toc-text">5.2 React.cloneElement克隆元素</span></a></li></ol></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-react-children" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">浅析React children</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2019.09.01</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 1.9k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 8分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、子组件"><a href="#一、子组件" class="headerlink" title="一、子组件"></a>一、子组件</h2><blockquote>
<p>我们有一个组件 <code>&lt;Grid /&gt;</code> 包含了几个组件 <code>&lt;Row /&gt;</code> 。你可能会这么使用它</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">Grid</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">Row</span> /&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">Row</span> /&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">Row</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">Grid</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>这三个 <code>Row</code> 组件都成为了 <code>Grid</code> 的 <code>props.children</code> 。使用一个表达式容器，父组件就能够渲染它们的子组件</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Grid</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>&#123;this.props.children&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>父组件也能够决定不渲染任何的子组件或者在渲染之前对它们进行操作。例如，这个 <code>&lt;Fullstop /&gt;</code> 组件就没有渲染它的子组件</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Fullstop</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">h1</span>&gt;</span>Hello world!<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="二、任何东西都能是一个child"><a href="#二、任何东西都能是一个child" class="headerlink" title="二、任何东西都能是一个child"></a>二、任何东西都能是一个child</h2><blockquote>
<p><code>React</code>中的<code>Children</code>不一定是组件，它们可以使任何东西。例如，我们能够将上面的文字作为<code>children</code>传递我们的 <code>&lt;Grid /&gt;</code>组件</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">Grid</span>&gt;</span>Hello world!<span class="tag">&lt;/<span class="name">Grid</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>JSX</code>将会自动删除每行开头和结尾的空格，以及空行。它还会把字符串中间的空白行压缩为一个空格</li>
<li>你也可以将多种类型的<code>children</code>完美的结合在一起：</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">Grid</span>&gt;</span></span><br><span class="line">  Here is a row:</span><br><span class="line">  <span class="tag">&lt;<span class="name">Row</span> /&gt;</span></span><br><span class="line">  Here is another row:</span><br><span class="line">  <span class="tag">&lt;<span class="name">Row</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">Grid</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="三、child-的功能"><a href="#三、child-的功能" class="headerlink" title="三、child 的功能"></a>三、child 的功能</h2><ul>
<li>我们能够传递任何的JavaScript表达式作为children，包括函数</li>
</ul>
<blockquote>
<p>为了说明这种情况，以下是一个组件，它将执行一个传递过来的作为child的函数</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Executioner</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="comment">// See how we're calling the child as a function?</span></span><br><span class="line">    <span class="comment">//                        ↓</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.props.children()</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>你会像这样的使用这个组件</p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">Executioner</span>&gt;</span></span><br><span class="line">  &#123;() =&gt; <span class="tag">&lt;<span class="name">h1</span>&gt;</span>Hello World!<span class="tag">&lt;/<span class="name">h1</span>&gt;</span>&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">Executioner</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="四、操作children"><a href="#四、操作children" class="headerlink" title="四、操作children"></a>四、操作children</h2><blockquote>
<p>从本质上来讲， <code>props.children</code> 可以使任何的类型，比如数组、函数、对象等</p>
</blockquote>
<blockquote>
<p>React提供了一系列的函数助手来使得操作children更加方便</p>
</blockquote>
<h3 id="4-1-循环"><a href="#4-1-循环" class="headerlink" title="4.1 循环"></a>4.1 循环</h3><blockquote>
<p>两个最显眼的函数助手就是 <code>React.Children.map</code> 以及 <code>React.Children.forEach</code>。它们在对应数组的情况下能起作用，除此之外，当函数、对象或者任何东西作为<code>children</code>传递时，它们也会起作用</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">IgnoreFirstChild</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">const</span> children = <span class="keyword">this</span>.props.children</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;div&gt;</span><br><span class="line">        &#123;React.Children.map(children, (child, i) =&gt; &#123;</span><br><span class="line">          <span class="comment">// Ignore the first child</span></span><br><span class="line">          <span class="keyword">if</span> (i &lt; <span class="number">1</span>) <span class="keyword">return</span></span><br><span class="line">          <span class="keyword">return</span> child</span><br><span class="line">        &#125;)&#125;</span><br><span class="line">      &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">    )</span></span><br><span class="line"><span class="regexp">  &#125;</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>&lt;IgnoreFirstChild /&gt;</code> 组件在这里会遍历所有的<code>children</code>，忽略第一个<code>child</code>然后返回其他的</p>
</blockquote>
<figure class="highlight"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">IgnoreFirstChild</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">h1</span>&gt;</span>First<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">h1</span>&gt;</span>Second<span class="tag">&lt;/<span class="name">h1</span>&gt;</span> // <span class="tag">&lt;<span class="name">-</span> <span class="attr">Only</span> <span class="attr">this</span> <span class="attr">is</span> <span class="attr">rendered</span></span></span><br><span class="line">&lt;/IgnoreFirstChild&gt;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>在这种情况下，我们也可以使用<code></code>this.props.children.map<code>的方法。但将一个函数作为child传递过来将会发生什么呢？</code>this.props.children` 会是一个函数而不是一个数组，接着我们就会产生一个error</p>
</blockquote>
<blockquote>
<p>然而使用 <code>React.Children.map</code>函数，无论什么都不会报错</p>
</blockquote>
<figure class="highlight"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">IgnoreFirstChild</span>&gt;</span></span><br><span class="line">  &#123;() =&gt; <span class="tag">&lt;<span class="name">h1</span>&gt;</span>First<span class="tag">&lt;/<span class="name">h1</span>&gt;</span>&#125; // <span class="tag">&lt;<span class="name">-</span> <span class="attr">Ignored</span> 💪</span></span><br><span class="line">&lt;/IgnoreFirstChild&gt;</span><br></pre></td></tr></table></figure>
<h3 id="4-2-计数"><a href="#4-2-计数" class="headerlink" title="4.2 计数"></a>4.2 计数</h3><blockquote>
<p>因为<code>this.props.children</code> 可以是任何类型的，检查一个组件有多少个<code>children</code>是非常困难的。天真的使用 <code>this.props.children.length</code> ，当传递了字符串或者函数时程序便会中断。假设我们有个child：”Hello World!” ，但是使用 <code>.length</code> 的方法将会显示为12。</p>
</blockquote>
<p>这就是为什么我们有 <code>React.Children.count</code> 方法的原因</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ChildrenCounter</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">p</span>&gt;</span>React.Children.count(this.props.children)<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>无论时什么类型它都会返回<code>children</code>的数量</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">// Renders "1"</span><br><span class="line"><span class="tag">&lt;<span class="name">ChildrenCounter</span>&gt;</span></span><br><span class="line">  Second!</span><br><span class="line"><span class="tag">&lt;/<span class="name">ChildrenCounter</span>&gt;</span></span><br><span class="line"></span><br><span class="line">// Renders "2"</span><br><span class="line"><span class="tag">&lt;<span class="name">ChildrenCounter</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">p</span>&gt;</span>First<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">ChildComponent</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">ChildrenCounter</span>&gt;</span></span><br><span class="line"></span><br><span class="line">// Renders "3"</span><br><span class="line"><span class="tag">&lt;<span class="name">ChildrenCounter</span>&gt;</span></span><br><span class="line">  &#123;() =&gt; <span class="tag">&lt;<span class="name">h1</span>&gt;</span>First!<span class="tag">&lt;/<span class="name">h1</span>&gt;</span>&#125;</span><br><span class="line">  Second!</span><br><span class="line">  <span class="tag">&lt;<span class="name">p</span>&gt;</span>Third!<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">ChildrenCounter</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="4-3-转换为数组"><a href="#4-3-转换为数组" class="headerlink" title="4.3 转换为数组"></a>4.3 转换为数组</h3><blockquote>
<p>如果以上的方法你都不适合，你能将<code>children</code>转换为数组通过 <code>React.Children.toArray</code> 方法。如果你需要对它们进行排序，这个方法是非常有用的</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Sort</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">const</span> children = React.Children.toArray(<span class="keyword">this</span>.props.children)</span><br><span class="line">    <span class="comment">// Sort and render the children</span></span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;children.sort().join(' ')&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">Sort</span>&gt;</span></span><br><span class="line">  // We use expression containers to make sure our strings</span><br><span class="line">  // are passed as three children, not as one string</span><br><span class="line">  &#123;'bananas'&#125;&#123;'oranges'&#125;&#123;'apples'&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">Sort</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>上例会渲染为三个排好序的字符串</p>
<h3 id="4-4-执行单一child"><a href="#4-4-执行单一child" class="headerlink" title="4.4 执行单一child"></a>4.4 执行单一child</h3><blockquote>
<p>如果你回过来想刚才的 <code>&lt;Executioner /&gt;</code> 组件，它只能在传递单一<code>child</code>的情况下使用，而且<code>child</code>必须为函数</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Executioner</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.props.children()</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>我们可以试着去强制执行 <code>propTypes</code> ，就像下面这样</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">Executioner.propTypes = &#123;</span><br><span class="line">  children: React.PropTypes.func.isRequired,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>这会使控制台打印出一条消息，部分的开发者将会把它忽视。相反的，我们可以使用在 <code>render</code> 里面使用 <code>React.Children.only</code></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Executioner</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">return</span> React.Children.only(<span class="keyword">this</span>.props.children)()</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样只会返回一个<code>child</code>。如果不止一个<code>child</code>，它就会抛出错误，让整个程序陷入中断——完美的避开了试图破坏组件的懒惰的开发者</p>
<h2 id="五、编辑children"><a href="#五、编辑children" class="headerlink" title="五、编辑children"></a>五、编辑children</h2><blockquote>
<p>我们可以将任意的组件呈现为<code>children</code>，但是任然可以用父组件去控制它们，而不是用渲染的组件。为了说明这点，让我们举例一个 能够拥有很多 <code>RadioButton</code> 组件的 <code>RadiaGroup</code> 组件</p>
</blockquote>
<blockquote>
<p><code>RadioButtons</code> 不会从 <code>RadioGroup</code> 本身上进行渲染，它们只是作为<code>children</code>使用。这意味着我们将会有这样的代码</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">render() &#123;</span><br><span class="line">  <span class="keyword">return</span>(</span><br><span class="line">    &lt;RadioGroup&gt;</span><br><span class="line">      &lt;RadioButton value=<span class="string">"first"</span>&gt;First&lt;<span class="regexp">/RadioButton&gt;</span></span><br><span class="line"><span class="regexp">      &lt;RadioButton value="second"&gt;Second&lt;/</span>RadioButton&gt;</span><br><span class="line">      &lt;RadioButton value=<span class="string">"third"</span>&gt;Third&lt;<span class="regexp">/RadioButton&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>RadioGroup&gt;</span><br><span class="line">  )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>这段代码有一个问题。<code>input</code> 没有被分组</li>
<li>为了把 <code>input</code> 标签弄到同组，必须拥有相同的<code>name</code> 属性。当然我们可以直接给每个<code>RadioButton</code> 的<code>name</code> 赋值</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">RadioGroup</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">RadioButton</span> <span class="attr">name</span>=<span class="string">"g1"</span> <span class="attr">value</span>=<span class="string">"first"</span>&gt;</span>First<span class="tag">&lt;/<span class="name">RadioButton</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">RadioButton</span> <span class="attr">name</span>=<span class="string">"g1"</span> <span class="attr">value</span>=<span class="string">"second"</span>&gt;</span>Second<span class="tag">&lt;/<span class="name">RadioButton</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">RadioButton</span> <span class="attr">name</span>=<span class="string">"g1"</span> <span class="attr">value</span>=<span class="string">"third"</span>&gt;</span>Third<span class="tag">&lt;/<span class="name">RadioButton</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">RadioGroup</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="5-1-改变children的属性"><a href="#5-1-改变children的属性" class="headerlink" title="5.1 改变children的属性"></a>5.1 改变children的属性</h3><blockquote>
<p>在<code>RadioGroup</code> 中我们将会添加一个叫做 <code>renderChildren</code> 的方法，在这里我们编辑<code>children</code>的属性</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RadioGroup</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="keyword">super</span>()</span><br><span class="line">    <span class="comment">// Bind the method to the component context</span></span><br><span class="line">    <span class="keyword">this</span>.renderChildren = <span class="keyword">this</span>.renderChildren.bind(<span class="keyword">this</span>)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  renderChildren() &#123;</span><br><span class="line">    <span class="comment">// <span class="doctag">TODO:</span> Change the name prop of all children</span></span><br><span class="line">    <span class="comment">// to this.props.name</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.props.children</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;div className=<span class="string">"group"</span>&gt;</span><br><span class="line">        &#123;<span class="keyword">this</span>.renderChildren()&#125;</span><br><span class="line">      &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">    )</span></span><br><span class="line"><span class="regexp">  &#125;</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>让我们开始遍历<code>children</code>获得每个<code>child</code></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">renderChildren() &#123;</span><br><span class="line">  <span class="keyword">return</span> React.Children.map(<span class="keyword">this</span>.props.children, child =&gt; &#123;</span><br><span class="line">    <span class="comment">// <span class="doctag">TODO:</span> Change the name prop to this.props.name</span></span><br><span class="line">    <span class="keyword">return</span> child</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们如何编辑它们的属性呢？</p>
<h3 id="5-2-React-cloneElement克隆元素"><a href="#5-2-React-cloneElement克隆元素" class="headerlink" title="5.2 React.cloneElement克隆元素"></a>5.2 React.cloneElement克隆元素</h3><blockquote>
<p><code>React.cloneElement</code> 会克隆一个元素。我们将想要克隆的元素当作第一个参数，然后将想要设置的属性以对象的方式作为第二个参数。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> cloned = React.cloneElement(element, &#123;</span><br><span class="line">  <span class="keyword">new</span>: <span class="string">'yes!'</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p><strong>React.cloneElement参数</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">React.cloneElement(</span><br><span class="line">  element,</span><br><span class="line">  [props],</span><br><span class="line">  [...children]</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<ul>
<li>第一个参数：element</li>
<li>必须是一个存在的React组件或者原生DOM，以下都可以</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">React.cloneElement(<span class="tag">&lt;<span class="name">div</span> /&gt;</span>)</span><br><span class="line">React.cloneElement(<span class="tag">&lt;<span class="name">Child</span> /&gt;</span>)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>但我们通常发现用的最多的是搭配<code>React.Children.map</code>和<code>this.props.children</code>使用，如下</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">React.Children.map(<span class="keyword">this</span>.props.children,child=&gt;&#123;</span><br><span class="line">    React.cloneElement(child,&#123;...props&#125;,children)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>这正是我们的 <code>RadioGroup</code> 所需的。我们克隆所有的<code>child</code>并且设置<code>name</code> 属性</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">renderChildren() &#123;</span><br><span class="line">  <span class="keyword">return</span> React.Children.map(<span class="keyword">this</span>.props.children, child =&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> React.cloneElement(child, &#123;</span><br><span class="line">      name: <span class="keyword">this</span>.props.name</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>最后一步就是传递一个唯一的 <code>name</code> 给<code>RadioGroup</code></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;RadioGroup name=<span class="string">"g1"</span>&gt;</span><br><span class="line">  &lt;RadioButton value=<span class="string">"first"</span>&gt;First&lt;<span class="regexp">/RadioButton&gt;</span></span><br><span class="line"><span class="regexp">  &lt;RadioButton value="second"&gt;Second&lt;/</span>RadioButton&gt;</span><br><span class="line">  &lt;RadioButton value=<span class="string">"third"</span>&gt;Third&lt;<span class="regexp">/RadioButton&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>RadioGroup&gt;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>没有手动添加 <code>name</code> 属性给所有的 <code>RadioButton</code> ，我们只是告诉了 <code>RadioGroup</code> 所需的<code>name</code>而已。</p>
</blockquote>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2019/08/31/git-review/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2019/09/01/await-foreach/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
